using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Routing;

namespace ExtendedMvc {
	/// <summary>
	/// Extensions to ModelViewHelper
	/// </summary>
	public static class AjaxFormExtensions {

		public static ModelViewForm<T> Form<T>(this ModelViewAjaxHelper<T> ajax, string formAction = null, AjaxOptions ajaxOptions = null, IDictionary<string, object> ajaxAttributes = null) where T : class {
			var link = ajax.ViewContext.HttpContext.Request.RawUrl;
			if (formAction != null) link = UrlHelper.GenerateContentUrl(formAction, ajax.ViewContext.HttpContext);
			return ModelViewForm<T>.Create(ajax, link, ajaxOptions, ajaxAttributes);
		}

		public static ModelViewForm<T> ActionForm<T>(this ModelViewAjaxHelper<T> ajax, string actionName = null, string controllerName = null, object routeValues = null, AjaxOptions ajaxOptions = null, IDictionary<string, object> ajaxAttributes = null) where T : class {
			var values = routeValues is RouteValueDictionary ? routeValues as RouteValueDictionary : new RouteValueDictionary(routeValues);
			var formAction = UrlHelper.GenerateUrl(null, actionName, controllerName, values, ajax.RouteCollection, ajax.ViewContext.RequestContext, true);
			return ajax.Form(formAction, ajaxOptions, ajaxAttributes);
		}

		public static ModelViewForm<T> RouteForm<T>(this ModelViewAjaxHelper<T> ajax, string routeName = null, object routeValues = null, AjaxOptions ajaxOptions = null, IDictionary<string, object> ajaxAttributes = null) where T : class {
			var values = routeValues is RouteValueDictionary ? routeValues as RouteValueDictionary : new RouteValueDictionary(routeValues);
			string formAction = UrlHelper.GenerateUrl(routeName, null, null, values, ajax.RouteCollection, ajax.ViewContext.RequestContext, false);
			return ajax.Form(formAction, ajaxOptions, ajaxAttributes);
		}
	}
}
